<?php
namespace app\api\library;

use think\facade\Db;
use think\Exception;
use app\common\library\MpPay;
use app\common\model\Order;
use app\common\model\Cart;
use app\admin\model\User;
use app\admin\model\UserMoneyLog;
use app\admin\model\UserScoreLog;
use app\common\model\trade;

class OrderPayment{
    public static function order($out_trade_no){
        Db::startTrans();
        try{
            $cart = Cart::where('out_trade_no',$out_trade_no)->find();
            if(empty( $cart)){
                throw new Exception('订单异常');
            }
            if($cart['status'] != '2'){
                throw new Exception('订单状态错误');   
            }
            $message = MpPay::query($out_trade_no);
            if( $message === false){
                throw new Exception('商户订单查询失败');
            }
            
            if($message['trade_state'] == 'SUCCESS' && $message['payer']['openid'] == $cart['openid']){
                $cart->status = '3';
                $cart->save();
                $order = new Order();
                $order->user_id = $cart['user_id'];
                $order->out_trade_no = $out_trade_no;
                $order->product_id = $cart['goods_id'];
                $order->title = $cart['goods_title'];
                $order->type ='wechat';
                $order->price = $cart['price'];
                $order->gift = $cart['gift'];
                $order->total = $message['amount']['total'];
                $order->pay_time = time();
                $order->pay_total = $message['amount']['pay_total'];
                $order->pay_status = 1;
                $order->product = json_encode($cart);
                $order->transaction_id = $message['transaction_id'];
                $order->status = 1;
                $order->save();
                if($cart['price']>0){
                    Trade::create([
                        'user_id'=> $cart['user_id'],
                        'trade_type'=>'recharge',
                        'order_id'=> $order->id,
                        'type'=>'wechat',
                        'balance'=> $cart['price'],
                        'remark'=>'充值订单:'.$cart['goods_title'].'-'.$cart['price'].'元',
                    ]);
                }
                if($cart['gift'] > 0){
                    Trade::create([
                        'user_id'=> $cart['user_id'],
                        'trade_type'=>'recharge',
                        'order_id'=> $order->id,
                        'type'=>'gift',
                        'balance'=> $cart['price'],
                        'remark'=>'充值订单:'.$cart['goods_title'].'-赠送'.$cart['gift'].'元',
                    ]);
                }
                if($cart['goods_id'] == 1){
                    Trade::create([
                        'user_id'=> $cart['user_id'],
                        'trade_type'=>'expense',
                        'order_id'=> $order->id,
                        'type'=>'wechat',
                        'balance'=> 30,
                        'remark'=>'普卡押金30元',
                    ]);
                }
                if($cart['goods_id'] == 2){
                    UserMoneyLog::create([
                        'user_id'=> $cart['user_id'],
                        'money'=>100,
                        'memo'=>'充值订单:'.$cart['goods_title'].'-赠送100元电瓶抵扣券'
                    ]);
                    UserScoreLog::create([
                        'user_id'=> $cart['user_id'],
                        'score'=>200,
                        'memo'=>'充值订单:'.$cart['goods_title'].'-赠送200水果积分券'
                    ]);
                    $user = User::find($cart['user_id']);
                    $user->group_id = 2;
                    $user->save();
                }
                self::authUser($cart['user_id']);
                Db::commit();
                return true;
            }else{
                throw new Exception('订单支付失败');
            }
        }catch(Exception $e){
            Db::rollback();
            return false;
        }
    }
    public static function authUser($user_id){
        $user = User::find($user_id);
        $timestamp = time();
        if($user['auth_start'] && $user['auth_end']){
            $authEnd = strtotime($user['auth_end']);
            if( $authEnd < $timestamp){
                $user->auth_start = date('Y-m-d');
                $user->auth_end = date('Y-m-d',strtotime('+1 year', $timestamp));
            }else{
                $user->auth_end = date('Y-m-d',strtotime('+1 year', $authEnd));
            }

        }else{
            $user->auth_start = date('Y-m-d');
            $user->auth_end = date('Y-m-d',strtotime('+1 year', $timestamp));
        }
        $user->save();
    }
}